clear all
set more off
snapshot erase _all

global path "~/shared_space/dbaharc/BHOR-YugoslavianRefugees/"
qui do "${path}do_files/InitializeGlobals.do"

/********************/
/*** Prepare Data ***/
/********************/
use "${path}data/GermanYUGMigration.dta", clear
qui do "${path}do_files/InitializeVars.do"
keep if iso3=="YUG"


label var lnexp "$ log(exp) $"
label var lnexpplus1 "$ log(exp+1) $"
label var asinhexp "$ asinh(exp) $"

/*****************************************/
/* ROBUSTNESS AND OTHERS ON MAIN RESULTS */
/*****************************************/

//Table with exports to each region at a time
label var exptoeasiapac "East Asia and the Pacific"
label var exptoeeurope "Eastern Europe"
label var exptolac "Latin America and The Caribbean"
label var exptomeastnafr "Middle East and North Africa"
label var exptonamerica "North America"
label var exptosasia "South Asia"
label var exptossa "Sub-Saharan Africa"
label var exptoweurope "Western Europe"
do "${path}do_files/RegionsTable.do"

//Descriptive data to figure out to which regions there were more new (0 in 1990) exports
ds expto*, v(32)
local vlist = r(varlist)
foreach v of local vlist {
    g temp = `v'==0 if year==1990
    egen `v'zero1990 = mean(temp), by(product)
    di "Products with zero exports in 1990 (first line), and 2010 (second line) for `v'"
    count if `v'==0 & year==1990
    count if `v'==0 & year==2010 & `v'zero1990
    drop temp `v'zero1990
}


//Results using levels
preserve
local y1min2 = $y1-2
local y2plus2 = $y2+2
egen temp1 = total($expdv) if year>=`y1min2' & year<=$y1, by(product)
egen temp2 = total($expdv) if year>=$y2 & year<=`y2plus2', by(product)
g cumexp = temp1/3 if year==$y1
replace cumexp = temp2/3 if year==$y2
drop temp1 temp2
eststo, title(OLS): qui reghdfe cumexp  c.treat2000#c.$after if didsample19902005, $rhsoptions
//eststo, title(2SLS): qui reghdfe cumexp (c.treat2000#c.$after=c.treatIV#c.$after) if didsample19902005, $rhsoptions
estout, $estout_params_IV_txt 
eststo clear
restore

//Using an IV that excludes Bavaria
preserve
local y1min2 = $y1-2
local y2plus2 = $y2+2
egen temp1 = total($expdv) if year>=`y1min2' & year<=$y1, by(product)
egen temp2 = total($expdv) if year>=$y2 & year<=`y2plus2', by(product)
g cumexp = temp1/3 if year==$y1
replace cumexp = temp2/3 if year==$y2
drop temp1 temp2
replace lnexp = log(cumexp)
replace lnexpplus1 = log(cumexp+1)
replace asinhexp = asinh(cumexp)
replace treatIV = asinh(shareest_asyl_DEU_XBYBW_9195)
foreach v in lnexp lnexpplus1 asinhexp {
    local lbl`v' : variable label `v'
    eststo, title(`lbl`v''): qui reghdfe `v'  (c.treat2000#c.$after=c.treatIV#c.$after) if didsample19902005, $rhsoptions
}
estout, $estout_params_IV_txt //mgroups("OLS" "2SLS", $estout_mgroups_ops) 
estout using "${path}tables/DIDMainCumExp_IVxBYBW.tex", replace $estout_params_IV $estout_pre $estout_post
eststo clear
restore

//Fuzzy diff-in-diff test
preserve
local y1min2 = $y1-2
local y2plus2 = $y2+2
egen temp1 = total($expdv) if year>=`y1min2' & year<=$y1, by(product)
egen temp2 = total($expdv) if year>=$y2 & year<=`y2plus2', by(product)
g cumexp = temp1/3 if year==$y1
replace cumexp = temp2/3 if year==$y2
drop temp1 temp2
replace lnexp = log(cumexp)
replace lnexpplus1 = log(cumexp+1)
replace asinhexp = asinh(cumexp)

qui su treat2000, d
g treatmentgroup = treat2000>r(p25) if $didsample
g treatafter = treat2000*$after

fuzzydid lnexp treatmentgroup $after treatafter, did cluster(product)
fuzzydid lnexpplus1 treatmentgroup $after treatafter, did cluster(product)
fuzzydid asinhexp treatmentgroup $after treatafter, did cluster(product)
restore

//Excluding each one of the countries at a time, changing LHS
//foreach c in SRB BIH HRV SVN MKD {
foreach c in SVN MKD {
    preserve
    local y1min2 = $y1-2
    local y2plus2 = $y2+2
    replace expno`c'_xdeu = exp_xdeu if year>=`y1min2' & year<=$y1 & iso3=="YUG"
    //replace expno`c'_xdeu = 0 if expno`c'_xdeu<0 & iso3=="YUG"

    egen temp1 = total(expno`c'_xdeu) if year>=`y1min2' & year<=$y1, by(product)
    egen temp2 = total(expno`c'_xdeu) if year>=$y2 & year<=`y2plus2', by(product)
    g cumexp = temp1/3 if year==$y1
    replace cumexp = temp2/3 if year==$y2
    drop temp1 temp2

    replace lnexp = log(cumexp)
    replace lnexpplus1 = log(cumexp+1)
    replace asinhexp = asinh(cumexp)
    replace lnfdi = asinh(fdino`c')
    foreach v in lnexp lnexpplus1 asinhexp {
        local lbl`v' : variable label `v'
        eststo, title(`lbl`v''): qui reghdfe `v' c.treat2000#c.$after  if $didsample, $rhsoptions
        //eststo, title(`v'): qui reghdfe `v' (c.treat2000#c.$after = c.treatIV#c.$after)  if $didsample, $rhsoptions
     }
     //foreach v in lnexp lnexpplus1 asinhexp {
     //   eststo, title(`v'): qui reghdfe `v'  (c.treat2000#c.$after=c.treatIV#c.$after) if $didsample, $rhsoptions
     //}
     estout, $estout_params_IV_txt mgroups("OLS" "2SLS", $estout_mgroups_ops)
     //estout using "${path}tables/DIDMainCumExp_no`c'.tex", replace $estout_params_IV $estout_pre $estout_post mgroups("OLS" "2SLS", $estout_mgroups_ops)
     if "`c'"=="SVN" {
         estout using "${path}tables/DIDMainCumExp_noSVNMKD.tex", replace $estout_params $estout_pre_panelA
     }
     if "`c'"=="MKD" {
         estout using "${path}tables/DIDMainCumExp_noSVNMKD.tex", append $estout_params $estout_pre_panelB $estout_post
     }
     eststo clear
     restore
}

//Clustering at the industry (w93) 3-digit level
preserve
use "${path}data/key_corr_sitc2_sitc3_w93_unique.dta", clear
keep if year==1990
drop year
ren sitc2 product
tempfile sitcw93
save `sitcw93'
restore

merge m:1 product using `sitcw93', keep(master matched) nogen

preserve
replace w93_3 = product if mi(w93_3)
local y1min2 = $y1-2
local y2plus2 = $y2+2
egen temp1 = total($expdv) if year>=`y1min2' & year<=$y1, by(product)
egen temp2 = total($expdv) if year>=$y2 & year<=`y2plus2', by(product)
g cumexp = temp1/3 if year==$y1
replace cumexp = temp2/3 if year==$y2
drop temp1 temp2
replace lnexp = log(cumexp)
replace lnexpplus1 = log(cumexp+1)
replace asinhexp = asinh(cumexp)
foreach v in lnexp lnexpplus1 asinhexp {
    local lbl`v' : variable label `v'
    eststo, title(`lbl`v''): qui reghdfe `v' c.treat2000#c.$after  if $didsample, a(product year) cluster(w93_3)
}
foreach v in lnexp lnexpplus1 asinhexp {
    local lbl`v' : variable label `v'
    eststo, title(`lbl`v''): qui reghdfe `v'  (c.treat2000#c.$after=c.treatIV#c.$after) if $didsample, a(product year) cluster(w93_3) old
}
estout, $estout_params_IV_txt mgroups("OLS" "2SLS", $estout_mgroups_ops) 
estout using "${path}tables/DIDMainCumExpW93Cluster.tex", replace $estout_params_IV $estout_pre $estout_post mgroups("OLS" "2SLS", $estout_mgroups_ops) 
eststo clear
restore

//Using levels as treatment
preserve
egen temp1 = total($expdv) if year>=1985 & year<=1990, by(product)
egen temp2 = total($expdv) if year>=2005 & year<=2010, by(product)
g cumexp = temp1/6 if year==1990
replace cumexp = temp2/6 if year==2005
drop temp1 temp2
replace lnexp = log(cumexp)
replace lnexpplus1 = log(cumexp+1)
replace asinhexp = asinh(cumexp)
foreach v in lnexp lnexpplus1 asinhexp {
    local lbl`v' : variable label `v'
    eststo, title(`lbl`v''): qui reghdfe `v'  c.treat1995level#c.$after if didsample19902005, $rhsoptions
}
foreach v in lnexp lnexpplus1 asinhexp {
    eststo, title(`lbl`v''): qui reghdfe `v'  (c.treat1995level#c.$after=c.treatIV#c.$after) if didsample19902005, $rhsoptions
}
estout, $estout_params_IV_txt  mgroups("OLS" "2SLS", $estout_mgroups_ops) 
estout using "${path}tables/DIDMainCumExp_OtherTreat.tex", replace $estout_params_IV $estout_pre $estout_post mgroups("OLS" "2SLS", $estout_mgroups_ops) 
eststo clear
restore

//Check zeros in trade data
preserve
local y1min2 = $y1-2
local y2plus2 = $y2+2
egen temp1 = total($expdv) if year>=`y1min2' & year<=$y1, by(product)
egen temp2 = total($expdv) if year>=$y2 & year<=`y2plus2', by(product)
g cumexp = temp1/3 if year==$y1
replace cumexp = temp2/3 if year==$y2
drop temp1 temp2
ren cumexp exp3yr

keep product year $expdv exp3yr
rename $expdv exp
keep if year == $y1 | year == $y2
reshape wide exp exp3yr, i(product) j(year)
rename product product_code
merge 1:1 product_code using "${path}data/SITC4_Names.dta", keep(1 3) nogen
rename product_code product

count if exp3yr$y1 == 0
count if exp3yr$y2 == 0 
count if exp3yr$y1 == 0 & exp3yr$y2 == 0 
count if exp3yr$y2 == 0 | exp3yr$y2 == 0 

/*Show products that were introduced*/
count if exp3yr$y1 == 0 & exp3yr$y2 != 0
list product product_name if exp3yr$y1 == 0 & exp3yr$y2 != 0, sep(100)

use "${path}data/mpd2018.dta", clear
keep if year==$y1
keep rgdpnapc countrycode year
ren rgdpnapc gdp_pcap_pp_kd
ren countrycode iso3
tempfile wdigdp
save `wdigdp'

/* Read in trade data for all countries */
use "${path}data/GermanYUGMigration.dta", clear
/* Plot # of products in pre-period */
egen pre_exp = total($expdv) if year >= 1988 & year <= 1990, by(iso3 product)
keep if year >= 1988 & year <= 1990 & pre_exp > 0 & pre_exp < .
keep pre_ex iso3 product 
duplicates drop
isid iso3 product
contract iso3 
gen freq_xyug = _freq if iso3 != "YUG"
gen yug_freq = _freq if iso3 == "YUG"
graph bar freq_xyug yug_freq, over(iso3, sort(_freq) label(angle(90) labsize(vsmall))  ) ///
	ytitle("Non-zero products (1988-1990)") ///
	xsize(13) ysize(5) legend(off) nofill
graph export "${path}/graphs/ProductNums.eps", replace

/*Plot # of exports vs gdp per capita*/
merge 1:1 iso3 using `wdigdp', keep(master matched) nogen
g ln_gdp_pc = log(gdp_pcap_pp_kd)
twoway (scatter _freq ln_gdp_pc if iso3 != "YUG", mlab(iso3) mlabcolor(gs10) mlabsize(vsmall) msymbol(none)) ///
       (scatter _freq ln_gdp_pc  if iso3 == "YUG", mlab(iso3)), ///
	legend(off) ytitle("Non-zero export products (1988-1990)") xtitle("GDP per Capita PPP (1990, logs)")
graph export "${path}/graphs/ProductNumsvsGDP.eps", replace
restore

//Main Specification when exports>0
preserve
local y1min2 = $y1-2
local y2plus2 = $y2+2
egen temp1 = total($expdv) if year>=`y1min2' & year<=$y1, by(product)
egen temp2 = total($expdv) if year>=$y2 & year<=`y2plus2', by(product)
g cumexp = temp1/3 if year==$y1
replace cumexp = temp2/3 if year==$y2
drop temp1 temp2
replace lnexp = log(cumexp)
replace lnexpplus1 = log(cumexp+1)
replace asinhexp = asinh(cumexp)
foreach v in lnexpplus1 asinhexp {
    local lbl`v' : variable label `v'
    eststo, title(`lbl`v''): qui reghdfe `v' c.treat2000#c.$after  if $didsample & `v'>0, $rhsoptions
}
foreach v in lnexpplus1 asinhexp {
    local lbl`v' : variable label `v'
    eststo, title(`lbl`v''): qui reghdfe `v'  (c.treat2000#c.$after=c.treatIV#c.$after) if $didsample & `v'>0, $rhsoptions
}
estout, $estout_params_IV_txt  mgroups("OLS" "2SLS", pattern(1 0 1 0) prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span}))
estout using "${path}tables/DIDMainCumExp_expnonzero.tex", replace $estout_params_IV $estout_pre $estout_post  mgroups("OLS" "2SLS", pattern(1 0 1 0) prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span}))
eststo clear
restore

//Main specification cummulative exports, 3 years - no products under 25,000 in pre-period
preserve
local y1min2 = $y1-2
local y2plus2 = $y2+2
egen temp1 = total($expdv) if year>=`y1min2' & year<=$y1, by(product)
egen temp2 = total($expdv) if year>=$y2 & year<=`y2plus2', by(product)
g cumexp = temp1/3 if year==$y1
replace cumexp = temp2/3 if year==$y2
drop temp1 temp2
replace lnexp = log(cumexp)
replace lnexpplus1 = log(cumexp+1)
replace asinhexp = asinh(cumexp)
gen to_use_temp = cumexp >= 25000 if year == 1990
bys product: egen to_use = min(to_use_temp)
count if year == 1990 & to_use == 0
foreach v in lnexp lnexpplus1 asinhexp {
    local lbl`v' : variable label `v'
    eststo, title(`lbl`v''): qui reghdfe `v' c.treat2000#c.$after   if $didsample & to_use, $rhsoptions
}
foreach v in lnexp lnexpplus1 asinhexp {
    eststo, title(`lbl`v''): qui reghdfe `v'  (c.treat2000#c.$after=c.treatIV#c.$after) if $didsample & to_use, $rhsoptions
}
estout, $estout_params_IV_txt mgroups("OLS" "2SLS", $estout_mgroups_ops) 
estout using "${path}tables/DIDMainCumExp_above25K.tex", replace $estout_params_IV $estout_pre $estout_post mgroups("OLS" "2SLS", $estout_mgroups_ops) 
eststo clear
restore

/*************/
/*** SCALE ***/
/*************/
// Per-capita LHS
preserve
egen temp1 = total(exppc_xdeu) if year>=1988 & year<=1990, by(product)
egen temp2 = total(exppc_xdeu) if year>=2005 & year<=2007, by(product)
g cumexp = temp1/3 if year==1990
replace cumexp = temp2/3 if year==2005
replace lnexp = log(cumexp)
replace lnexpplus1 = log(cumexp+1)
replace asinhexp = asinh(cumexp)
drop temp1 temp2 cumexp
foreach v in lnexp lnexpplus1 asinhexp {
    local lbl`v' : variable label `v'
    eststo, title(`lbl`v''): qui reghdfe `v' c.treat2000#c.$after if didsample19902005, $rhsoptions
}
foreach v in lnexp lnexpplus1 asinhexp {
    eststo, title(`lbl`v''): qui reghdfe `v' (c.treat2000#c.$after=c.treatIV#c.$after)  if didsample19902005, $rhsoptions
}
estout, $estout_params_txt mgroups("OLS" "2SLS", $estout_mgroups_ops) 
estout using "${path}tables/DIDPerCapitaLHS.tex", replace $estout_params_IV $estout_pre $estout_post mgroups("OLS" "2SLS", $estout_mgroups_ops) 
eststo clear
restore

// Per-capita RHS
//Note: it divides the treatment by population in 1990 in MILLIONS (see InitializeVars.do)
//population from madisson is already in thousands. Dividing by thousand again results in millions.
preserve
egen temp1 = total($expdv) if year>=1988 & year<=1990, by(product)
egen temp2 = total($expdv) if year>=2005 & year<=2007, by(product)
g cumexp = temp1/3 if year==1990
replace cumexp = temp2/3 if year==2005
replace lnexp = log(cumexp)
replace lnexpplus1 = log(cumexp+1)
replace asinhexp = asinh(cumexp)
drop temp1 temp2 cumexp
foreach v in lnexp lnexpplus1 asinhexp {
    local lbl`v' : variable label `v'
    eststo, title(`lbl`v''): qui reghdfe `v' c.treat2000pc#c.$after  if didsample19902005, $rhsoptions
}
foreach v in lnexp lnexpplus1 asinhexp {
    local lbl`v' : variable label `v'
    eststo, title(`lbl`v''): qui reghdfe `v' (c.treat2000pc#c.$after=c.treatIV#c.$after)  if didsample19902005, $rhsoptions
}
estout, $estout_params_IV_txt mgroups("OLS" "2SLS", $estout_mgroups_ops) 
estout using "${path}tables/DIDPerCapitaRHS.tex", replace $estout_params_IV $estout_pre $estout_post mgroups("OLS" "2SLS", $estout_mgroups_ops) 
eststo clear
restore

//Labor intensive vs. capital intensive
preserve
g c_lp = - c_kp
label var c_lp  "Labor Intensity"
foreach v in lnexp lnexpplus1 asinhexp {
    local lbl`v' : variable label `v'
    eststo, title(`lbl`v''): qui reghdfe `v'  c.treat2000#c.$after c.treat2000#c.$after#c.c_lp  if $didsample, $rhsoptions
}
foreach v in lnexp lnexpplus1 asinhexp {
    eststo, title(`lbl`v''): qui reghdfe `v'  (c.treat2000#c.$after c.treat2000#c.$after#c.c_lp=c.treatIV#c.$after c.treatIV#c.$after#c.c_lp)  if $didsample, $rhsoptions
}
estout, $estout_params_IV_txt mgroups("OLS" "2SLS", $estout_mgroups_ops) 
estout using "${path}tables/DIDMainCumExpProductTypeLaborInt.tex", replace ///
	$estout_params_IV $estout_pre $estout_post  rename(c.treat2000#c.$after TreatmentXAfter c.treat2000#c.$after#c.c_lp treatXafterXlaborint) ///
        mgroups("OLS" "2SLS", $estout_mgroups_ops) 
eststo clear
restore

/*******************/
/*** CONVERGENCE ***/
/*******************/
/* Main specification with convergence control*/
preserve
local y1min2 = $y1-2
local y2plus2 = $y2+2
egen temp1 = total($expdv) if year>=`y1min2' & year<=$y1, by(product)
egen temp2 = total($expdv) if year>=$y2 & year<=`y2plus2', by(product)
g cumexp = temp1/3 if year==$y1
replace cumexp = temp2/3 if year==$y2
drop temp1 temp2
replace lnexp = log(cumexp)
replace lnexpplus1 = log(cumexp+1)
replace asinhexp = asinh(cumexp)
foreach v in lnexp lnexpplus1 asinhexp {
    local lbl`v' : variable label `v'
    eststo, title(`lbl`v''): qui reghdfe `v' c.treat2000#c.$after c.germanexpshare1990#c.$after if $didsample, $rhsoptions
}
foreach v in lnexp lnexpplus1 asinhexp {
    local lbl`v' : variable label `v'
    eststo, title(`lbl`v''): qui reghdfe `v'  c.germanexpshare1990#c.$after (c.treat2000#c.$after=c.treatIV#c.$after) if $didsample, $rhsoptions
}
estout, $estout_params_IV_txt mgroups("OLS" "2SLS", $estout_mgroups_ops) 
estout using "${path}tables/DIDMainConvergenceCtrl.tex", replace $estout_params_IV $estout_pre $estout_post mgroups("OLS" "2SLS", $estout_mgroups_ops) 
eststo clear
restore

/*****************************/
/*** BILATERAL TRADE COSTS ***/
/*****************************/
//Heterogenous vs. homogenous products, rybcinsky effect
//- Homogenous vs heterogeneous, using the liberal definition (which maximize the number of homogeonus goods)
preserve
//g het = !inlist(h_con, "r", "w") if h_con != ""
//g homog = inlist(h_con, "r", "w") if h_con != ""
g het = !inlist(h_lib, "r", "w") if h_lib != ""
g homog = inlist(h_lib, "r", "w") if h_lib != ""

local y1min2 = $y1-2
local y2plus2 = $y2+2
egen temp1 = total($expdv) if year>=`y1min2' & year<=$y1, by(product)
egen temp2 = total($expdv) if year>=$y2 & year<=`y2plus2', by(product)
g cumexp = temp1/3 if year==$y1
replace cumexp = temp2/3 if year==$y2
drop temp1 temp2
replace lnexp = log(cumexp)
replace lnexpplus1 = log(cumexp+1)
replace asinhexp = asinh(cumexp)

foreach v in lnexp lnexpplus1 asinhexp {
    local lbl`v' : variable label `v'
    eststo, title(`lbl`v''): qui reghdfe `v'  c.treat2000#c.$after c.treat2000#c.$after#c.het  if $didsample, $rhsoptions
}
foreach v in lnexp lnexpplus1 asinhexp {
    local lbl`v' : variable label `v'
    eststo, title(`lbl`v''): qui reghdfe `v'  (c.treat2000#c.$after c.treat2000#c.$after#c.het=c.treatIV#c.$after c.treatIV#c.$after#c.het)  if $didsample, $rhsoptions
}
estout, $estout_params_IV_txt
estout using "${path}tables/DIDMainCumExpProductDiff.tex", replace ///
	$estout_params_IV $estout_pre $estout_post  rename(c.treat2000#c.$after TreatmentXAfter c.treat2000#c.$after#c.het treatXafterXdiff) ///
        mgroups("OLS" "2SLS", $estout_mgroups_ops) 
eststo clear
restore

//Using All Exports incl. to Germany on LHS
preserve
local y1min2 = $y1-2
local y2plus2 = $y2+2
egen temp1 = total(exp) if year>=`y1min2' & year<=$y1, by(product)
egen temp2 = total(exp) if year>=$y2 & year<=`y2plus2', by(product)
g cumexp = temp1/3 if year==$y1
replace cumexp = temp2/3 if year==$y2
drop temp1 temp2

replace lnexp = log(cumexp)
replace lnexpplus1 = log(cumexp+1)
replace asinhexp = asinh(cumexp)
foreach v in lnexp lnexpplus1 asinhexp {
    local lbl`v' : variable label `v'
    eststo, title(`lbl`v''): qui reghdfe `v' c.treat2000#c.$after   if $didsample, $rhsoptions
}
foreach v in lnexp lnexpplus1 asinhexp {
    local lbl`v' : variable label `v'
    eststo, title(`lbl`v''): qui reghdfe `v'   (c.treat2000#c.$after=c.treatIV#c.$after) if $didsample, $rhsoptions
}
estout, $estout_params_IV_txt mgroups("OLS" "2SLS", $estout_mgroups_ops) 
estout using "${path}tables/DIDMainCumExpDEU.tex", replace $estout_params_IV $estout_pre $estout_post mgroups("OLS" "2SLS", $estout_mgroups_ops) 
eststo clear
restore

//Imports of intermediate goods using I/O table
//Incorporation of IO coefficients in DatasetConstruction.do
preserve
local y1min2 = $y1-2
local y2plus2 = $y2+2
egen temp1 = total($expdv) if year>=`y1min2' & year<=$y1, by(product)
egen temp2 = total($expdv) if year>=$y2 & year<=`y2plus2', by(product)
g cumexp = temp1/3 if year==$y1
replace cumexp = temp2/3 if year==$y2
drop temp1 temp2

egen temp1 = total(ioimpdeu) if year>=`y1min2' & year<=$y1, by(product)
egen temp2 = total(ioimpdeu) if year>=$y2 & year<=`y2plus2', by(product)
g cumimp = temp1/3 if year==$y1
replace cumimp = temp2/3 if year==$y2
drop temp1 temp2
g lnioimpdeu = asinh(cumimp)

foreach v in lnexp lnexpplus1 asinhexp {
    local lbl`v' : variable label `v'
    eststo, title(`lbl`v''): qui reghdfe `v' c.treat2000#c.$after  lnioimpdeu if $didsample, $rhsoptions
}
foreach v in lnexp lnexpplus1 asinhexp {
    local lbl`v' : variable label `v'
    eststo, title(`lbl`v''): qui reghdfe `v'   lnioimpdeu (c.treat2000#c.$after=c.treatIV#c.$after) if $didsample, $rhsoptions
}
estout, $estout_params_IV_txt mgroups("OLS" "2SLS", $estout_mgroups_ops) 
estout using "${path}tables/DIDMainCumExpIOImports.tex", replace $estout_params_IV $estout_pre $estout_post mgroups("OLS" "2SLS", $estout_mgroups_ops) 
eststo clear
restore

/************************************/
/* CAPITAL FORMATION AND INVESTMENT */
/************************************/
/* Using German FDI stocks in Yugoslavia as control, panel A*/
preserve
local y1min2 = $y1-2
local y2plus2 = $y2+2
egen temp1 = total($expdv) if year>=`y1min2' & year<=$y1, by(product)
egen temp2 = total($expdv) if year>=$y2 & year<=`y2plus2', by(product)
g cumexp = temp1/3 if year==$y1
replace cumexp = temp2/3 if year==$y2
drop temp1 temp2
replace lnexp = log(cumexp)
replace lnexpplus1 = log(cumexp+1)
replace asinhexp = asinh(cumexp)
foreach v in lnexp lnexpplus1 asinhexp {
    local lbl`v' : variable label `v'
    eststo, title(`lbl`v''): qui reghdfe `v' c.treat2000#c.$after  lnfdi if $didsample, $rhsoptions
}
foreach v in lnexp lnexpplus1 asinhexp {
    local lbl`v' : variable label `v'
    eststo, title(`lbl`v''): qui reghdfe `v'   lnfdi (c.treat2000#c.$after=c.treatIV#c.$after) if $didsample, $rhsoptions
}
estout, $estout_params_IV_txt mgroups("OLS" "2SLS", $estout_mgroups_ops) 
estout using "${path}tables/DIDMainCumExpFDI.tex", replace $estout_params_IV $estout_pre_panelA  mgroups("OLS" "2SLS", $estout_mgroups_ops) 
eststo clear
restore

/*Using total / global FDI stocks in Yugoslavia as a control, panel B*/
preserve
use "${path}data/fdi_global_2005.dta", clear
ren FDI globalfdi
tempfile globalfdi
save `globalfdi'
restore

preserve
g sitc2 = floor(product/100)
merge m:1 sitc2 using `globalfdi', keep(matched master) nogen
replace globalfdi = 0 if mi(globalfdi)
replace globalfdi = . if year!=2005
replace globalfdi = 0 if year==1990
g lnglobalfdi = asinh(globalfdi)

local y1min2 = $y1-2
local y2plus2 = $y2+2
egen temp1 = total($expdv) if year>=`y1min2' & year<=$y1, by(product)
egen temp2 = total($expdv) if year>=$y2 & year<=`y2plus2', by(product)
g cumexp = temp1/3 if year==$y1
replace cumexp = temp2/3 if year==$y2
drop temp1 temp2

replace lnexp = log(cumexp)
replace lnexpplus1 = log(cumexp+1)
replace asinhexp = asinh(cumexp)
foreach v in lnexp lnexpplus1 asinhexp {
    local lbl`v' : variable label `v'
    eststo, title(`lbl`v''): qui reghdfe `v' c.treat2000#c.$after  lnglobalfdi if $didsample, $rhsoptions
}
foreach v in lnexp lnexpplus1 asinhexp {
    local lbl`v' : variable label `v'
    eststo, title(`lbl`v''): qui reghdfe `v'  lnglobalfdi (c.treat2000#c.$after=c.treatIV#c.$after) if $didsample, $rhsoptions
}
estout, $estout_params_IV_txt mgroups("OLS" "2SLS", $estout_mgroups_ops) 
estout using "${path}tables/DIDMainCumExpFDI.tex", append $estout_params_IV $estout_pre_panelB $estout_post mgroups("OLS" "2SLS", $estout_mgroups_ops) 
eststo clear
restore


/*Only FDI to show its positive coefficeint*/
global estout_params_fdi = `"cells(b(fmt(3)) se(star par fmt(3))) starlevels(* .1 ** .05 *** .01) varlabels(_cons Constant) label stats(N r2 prod_fe, fmt(0 2 2) labels("N" "r2" "Product FE"))  style(tex) collabels(none) posthead(\hline) prefoot(~\\)"'
global estout_params_fdi_txt = `"cells(b(fmt(3)) se(star par fmt(3))) starlevels(* .1 ** .05 *** .01) varlabels(_cons Constant) label stats(N r2 prod_fe, fmt(0 2  2)  labels("N" "r2" "Product FE"))"'

preserve
local y1min2 = $y1-2
local y2plus2 = $y2+2
egen temp1 = total($expdv) if year>=`y1min2' & year<=$y1, by(product)
egen temp2 = total($expdv) if year>=$y2 & year<=`y2plus2', by(product)
g cumexp = temp1/3 if year==$y1
replace cumexp = temp2/3 if year==$y2
drop temp1 temp2

replace lnexp = log(cumexp)
replace lnexpplus1 = log(cumexp+1)
replace asinhexp = asinh(cumexp)
foreach v in lnexp lnexpplus1 asinhexp {
    local lbl`v' : variable label `v'
    eststo, title(`lbl`v''): qui reghdfe `v' lnfdi if $didsample, $rhsoptions
    qui estadd local prod_fe "Y"

}
foreach v in lnexp lnexpplus1 asinhexp {
    local lbl`v' : variable label `v'
    eststo, title(`lbl`v''): qui reghdfe `v' lnfdi if $didsample, a(year) cluster(product)
    qui estadd local prod_fe "N"
}
estout, $estout_params_fdi_txt drop(_cons)
estout using "${path}tables/FDIOnly.tex", replace $estout_params_fdi $estout_pre $estout_post drop(_cons)
eststo clear
restore
twoway scatter asinhexp lnfdi if didsample19902005
graph export "${path}/graphs/FDIvsExports.eps", replace

//Using wages accumulated by Yugoslavians in each industry as control
//g lnglobalfdi = asinh(globalfdi)
/*
preserve
g lnwage = asinh(mig_rm_ls00_mlwage_mj)
local y1min2 = $y1-2
local y2plus2 = $y2+2
egen temp1 = total($expdv) if year>=`y1min2' & year<=$y1, by(product)
egen temp2 = total($expdv) if year>=$y2 & year<=`y2plus2', by(product)
g cumexp = temp1/3 if year==$y1
replace cumexp = temp2/3 if year==$y2
drop temp1 temp2

replace lnexp = log(cumexp)
replace lnexpplus1 = log(cumexp+1)
replace asinhexp = asinh(cumexp)
foreach v in lnexp lnexpplus1 asinhexp {
    eststo, title(`v'): qui reghdfe `v' c.treat2000#c.$after c.lnwage#c.$after if $didsample, $rhsoptions
}
foreach v in lnexp lnexpplus1 asinhexp {
    eststo, title(`v'): qui reghdfe `v'  c.lnwage#c.$after (c.treat2000#c.$after=c.treatIV#c.$after) if $didsample, $rhsoptions
}
estout, $estout_params_IV_txt mgroups("OLS" "2SLS", $estout_mgroups_ops) 
//estout using "${path}tables/DIDMainCumExpGlobalFDI.tex", replace $estout_params_IV $estout_pre $estout_post mgroups("OLS" "2SLS", $estout_mgroups_ops) 
eststo clear
restore
*/

/*********************/
/*** GLOBAL DEMAND ***/
/*********************/
preserve
local y1min2 = $y1-2
local y2plus2 = $y2+2
egen temp1 = total($expdv) if year>=`y1min2' & year<=$y1, by(product)
egen temp2 = total($expdv) if year>=$y2 & year<=`y2plus2', by(product)
g cumexp = temp1/3 if year==$y1
replace cumexp = temp2/3 if year==$y2
drop temp1 temp2
replace lnexp = log(cumexp)
replace lnexpplus1 = log(cumexp+1)
replace asinhexp = asinh(cumexp)
g temp = globalexpshare if year==1990
egen globalexpshare1990 = max(temp), by(product)
drop temp


foreach v in lnexp lnexpplus1 asinhexp {
    local lbl`v' : variable label `v'
    eststo, title(`lbl`v''): qui reghdfe `v' c.treat2000#c.$after   globalexpshare if didsample19902005, $rhsoptions
}
foreach v in lnexp lnexpplus1 asinhexp {
    local lbl`v' : variable label `v'
    eststo, title(`lbl`v''): qui reghdfe `v'   globalexpshare (c.treat2000#c.$after=c.treatIV#c.$after) if didsample19902005, $rhsoptions
}
estout, $estout_params_IV_txt mgroups("OLS" "2SLS", $estout_mgroups_ops) 
estout using "${path}tables/DIDMainCumExpGlobalExpControl.tex", replace $estout_params_IV $estout_pre $estout_post mgroups("OLS" "2SLS", $estout_mgroups_ops) 
eststo clear
restore

/***************************************/
/*** Excluding one product at a time ***/
/***************************************/
preserve
local y1min2 = $y1-2
local y2plus2 = $y2+2
egen temp1 = total($expdv) if year>=`y1min2' & year<=$y1, by(product)
egen temp2 = total($expdv) if year>=$y2 & year<=`y2plus2', by(product)
g cumexp = temp1/3 if year==$y1
replace cumexp = temp2/3 if year==$y2
drop temp1 temp2
replace lnexp = log(cumexp)
replace lnexpplus1 = log(cumexp+1)
replace asinhexp = asinh(cumexp)
qui levelsof product, local(plist)
matrix Plnexp = J(1,3,.)
matrix Plnexpplus1 = J(1,3,.)
matrix Pasinhexp = J(1,3,.)
foreach p of local plist {
    foreach v in lnexp lnexpplus1 asinhexp {
        qui reghdfe `v'  (c.treat2000#c.$after=c.treatIV#c.$after) if didsample19902005 & product!=`p', $rhsoptions
        matrix P`v' = [ P`v' \ `p',_b[c.treat2000#c.$after],_se[c.treat2000#c.$after]]
    }

}
restore

foreach v in lnexp lnexpplus1 asinhexp {
    local lbl`v' : variable label `v'
    local lbl`v' = subinstr("`lbl`v''","$","",.)
    preserve
    clear
    svmat P`v'
    drop if _n==1
    //local v lnexp
    ren (P`v'1 P`v'2 P`v'3) (product beta se)
    g ul = beta+1.96*se
    g ll = beta-1.96*se
    g n = (_n-1)
    labmask n, values(product)
    g sig99 = abs(beta/se) >= abs(2.58)
    g sig95 = abs(beta/se) >= abs(1.96) & !sig99
    g sig90 = abs(beta/se) >= abs(1.645) & !sig95
    g nosig = abs(beta/se) < abs(1.645)
    /*
    twoway  (rspike ul ll n, color(gs10) lw(vvthin)) (scatter beta n,  msymbol(triangle) msize(vtiny) mcolor(black)), scheme(s1color) ytitle("{&beta}{sup:DID} (95% CI)") ///
             xtitle(Excluded SITC code) xlabel(none) xmlabel(0(1)785,val angle(90) labsize(third_tiny)) name(`v', replace) yline(0, lc(red) lp(dash) lw(thin)) legend(off) ///
                 xsize(8) ysize(4)
    */
    twoway (scatter beta n if sig99,  msymbol(triangle) mcolor(gs0) msize(vtiny) mlabel(product) mlabsize(tiny) mlabcolor(gs0)) ///
             (scatter beta n if sig95,  msymbol(triangle) mcolor(gs8) msize(vtiny) mlabel(product) mlabsize(tiny)  mlabcolor(gs8)) ///
               (scatter beta n if sig90,  msymbol(triangle) mcolor(gs12) msize(vtiny) mlabel(product)  mlabsize(tiny) mlabcolor(gs12)) ///
                (scatter beta n if nosig,  msymbol(x) mcolor(red) msize(tiny) mlabel(product) mlabsize(tiny) mlabcolor(red)) ///
        , scheme(s1color) ytitle("{&beta}{sup:DID} (95% CI)") ///
             xtitle(Excluded SITC code) xlabel(none) legend(order(1 "Sig. 99%" 2 "Sig 95%" 3 "Sig. 90%" 4 "Not sig.") rows(1)) ///
                 xsize(8) ysize(4)
    //twoway (hist beta if nosig, b(786)) (hist beta if sig90, b(786)) (hist beta if sig95, b(786)) (hist beta if sig99, b(786)), scheme(s1color)
    //twoway (hist beta, freq) (hist beta if sig90, freq)
    graph export "${path}graphs/DIDExclSITC_`v'.eps", as(eps) replace
    //Again with title (and other formatting changes) for the graph combine
    if "`v'"=="asinhexp" {
        twoway (scatter beta n if sig99,  msymbol(triangle) mcolor(gs0) msize(vtiny) mlabel(product) mlabsize(tiny) mlabcolor(gs0)) ///
            (scatter beta n if sig95,  msymbol(triangle) mcolor(gs8) msize(vtiny) mlabel(product) mlabsize(tiny)  mlabcolor(gs8)) ///
                (scatter beta n if sig90,  msymbol(triangle) mcolor(gs12) msize(vtiny) mlabel(product)  mlabsize(tiny) mlabcolor(gs12)) ///
                    (scatter beta n if nosig,  msymbol(x) mcolor(red) msize(tiny) mlabel(product) mlabsize(tiny) mlabcolor(red)) ///
                        , scheme(s1color) ytitle("{&beta}{sup:DID} (95% CI)") title("`lbl`v''") ///
                            xtitle(Excluded SITC code) xlabel(none) name(`v', replace) legend(order(1 "Sig. 99%" 2 "Sig 95%" 3 "Sig. 90%" 4 "Not sig.") rows(1)) ///
                                xsize(8) ysize(3)
    } 
    else {
        twoway (scatter beta n if sig99,  msymbol(triangle) mcolor(gs0) msize(vtiny) mlabel(product) mlabsize(tiny) mlabcolor(gs0)) ///
            (scatter beta n if sig95,  msymbol(triangle) mcolor(gs8) msize(vtiny) mlabel(product) mlabsize(tiny)  mlabcolor(gs8)) ///
                (scatter beta n if sig90,  msymbol(triangle) mcolor(gs12) msize(vtiny) mlabel(product)  mlabsize(tiny) mlabcolor(gs12)) ///
                    (scatter beta n if nosig,  msymbol(x) mcolor(red) msize(tiny) mlabel(product) mlabsize(tiny) mlabcolor(red)) ///
                        , scheme(s1color) ytitle("{&beta}{sup:DID} (95% CI)") title("`lbl`v''") ///
                            xtitle(Excluded SITC code) xlabel(none) name(`v', replace) legend(off) ///
                                xsize(8) ysize(4)
    }
    restore    
}

graph combine lnexp lnexpplus1 asinhexp, rows(3) scheme(s1color) xsize(8) ysize(10)
graph export "${path}graphs/DIDExclSITC.eps", as(eps) replace

// USING TREATMENTS DIVIDED BY EARLY VS LATE RETURNEES
cap drop earlytreat notreat shareearly
g shareearly = mig_rm_ls00_r3_1991_1996/(mig_rm_ls00_r3_1991_1996+mig_rm_ls00_r3_1997_1999)
g notreat = mig_rm_ls00_r3_1991_1996==0 & mig_rm_ls00_r3_1997_1999==0

su shareearly, d
g earlytreat = shareearly>r(p90)
//g earlytreat = shareearly>=0.7

/*5 year periods*/
cap drop *_5y

local startyear = 1985
g period_5y = floor((year-`startyear')/5)+1 if year>=`startyear' & year<=2014
replace period_5y = . if year<`startyear'
egen insample_5y = tag(product period_5y) if !mi(period_5y)

egen exp_5y = total($expdv), by(period_5y product)
//egen exp_4y = total($expdv), by(period_4y product)
egen fdi_5y = total(fdi), by(period_5y product)
//egen fdi_4y = total(fdi), by(period_4y product)

//xi i.period_5y i.period_4y, noomit
xi i.period_5y, noomit

qui ds _Iperiod_5y*, v(32)
local vlist = r(varlist)
foreach v of local vlist {
    qui su year if `v'==1
    local min = r(min)
    local max = r(max)
    local maxmin = `max'-`min'
    label var `v' "Period `min'-`max'"
    replace exp_5y = exp_5y/`maxmin' if `v'==1
    replace fdi_5y = fdi_5y/`maxmin' if `v'==1
}

g lnexpplus1_5y = log(exp_5y+1)
g lnexp_5y = log(exp_5y)
g asinhexp_5y = asinh(exp_5y)
g lnfdi_5y = asinh(fdi_5y)

local i = 5 //i is the length of the periods, set to 5
global periodsDV "c._Iperiod_`i'y_1 c._Iperiod_`i'y_3 c._Iperiod_`i'y_4 c._Iperiod_`i'y_5  c._Iperiod_`i'y_6"
global convergenceperiods "c.germanexpshare1990#c._Iperiod_`i'y_1 c.germanexpshare1990#c._Iperiod_`i'y_3 c.germanexpshare1990#c._Iperiod_`i'y_4 c.germanexpshare1990#c._Iperiod_`i'y_5 c.germanexpshare1990#c._Iperiod_`i'y_6"
global convergenceperiods ""
foreach v in lnexp lnexpplus1 asinhexp {
    matrix R`v' = J(1,3,.)
    eststo `v'1, title("`v'"): qui reghdfe `v'_`i'y  $periodsDV  ///
        c.treat2000#($periodsDV) c.treat2000#c.earlytreat#($periodsDV) if ///
          insample_`i'y & !mi(period_`i'y) & period_`i'>=1, a(product) cluster(product) old
    foreach dv of global periodsDV {
        qui lincom _b[c.treat2000#c.`dv']
        matrix R`v' = R`v' \ [0, r(estimate),r(se)]
        qui lincom _b[c.treat2000#c.`dv']+_b[c.treat2000#c.earlytreat#c.`dv']
        matrix R`v' = R`v' \ [1, r(estimate),r(se)]
    }
}
estout, $estout_params_txt keep(c.treat*)
eststo clear

local missingperiod = 2
foreach v in lnexp lnexpplus1 asinhexp {
    preserve
    local lbl`v' : variable label `v'
    local lbl`v' = subinstr("`lbl`v''","$","",.)
    clear
    qui svmat R`v'
    drop if _n==1
    g period = floor((_n+1)/2)
    replace period = period+1 if period>=`missingperiod'
    qui tsset R`v'1 period
    tsfill
    qui replace R`v'2 = 0 if period==`missingperiod'
    label define period_lbl 1 "1985-1989" 2 "1990-1994" 3 "1995-1999" 4 "2000-2004" 5 "2005-2009" 6 "2010-2014", replace
    label val period period_lbl
    ren R`v'1 early
    ren R`v'2 beta
    ren R`v'3 se
    g ui = beta + 1.645*se
    g li = beta - 1.645*se

    sort period early
    g xvar = _n + (period-1)

    g sig90 = (ui>0 & li>0) | (ui<0 & li<0)
    /*
    twoway (bar beta xvar if !early & sig90, fcolor(gs10) lcolor(black)) ///
        (bar beta xvar if !early & !sig90, fcolor(white) lcolor(black)) ///
            (bar beta xvar if early & sig90, fcolor(gs5) lcolor(black)) ///
                (bar beta xvar if early & !sig90, fcolor(white) lcolor(black)), ///
        scheme(s1color) legend(order(1 "ATE" 3 "ATE Early Returnees") rows(2)) ///
            ytitle("{&beta}{sup:DID} (95% CI)") xtitle(Period) yline(0, lp(dot)) ///
                xline(5.5, lc(gs10)) note("Bar fill represent statistical significance with 90% confidence interval") ///
            xlabel(1.5 "1985-1989" 4.5 "1990-1994" 7.5 "1995-1999" 10.5 "2000-2004" ///
                   13.5 "2005-2009" 16.5 "2010-2014",angle(45) labsize(vsmall))
    */
    twoway  (rcap ui li xvar, lc(gs10)) ///
        (scatter beta xvar if !early, msymbol(square)) ///
            (scatter beta xvar if early, msymbol(triangle)), ///
        scheme(s1color) legend(order(2 "ATE" 3 "ATE Early Returnees") rows(2) size(vsmall)) ///
            ytitle("{&beta}{sup:DID} (95% CI)") xtitle(Period) yline(0, lp(dot)) ///
                xline(5.5, lc(gs10)) xlabel(1.5 "1985-1989" 4.5 "1990-1994" 7.5 "1995-1999" 10.5 "2000-2004" ///
                   13.5 "2005-2009" 16.5 "2010-2014",angle(45) labsize(vsmall)) title(`lbl`v'')
    tempfile `v'
    graph save ``v''.gph, replace
    restore
}


graph combine `lnexp'.gph `lnexpplus1'.gph `asinhexp'.gph, cols(3) scheme(s1color) ycommon 
graph export "${path}graphs/DIDEarlyLate.eps", as(eps) replace

